<?php

namespace App\Guards;

use App\Models\Common\FsCompanyUserMappingModel;
use App\Remote\Rms\RmsUserRemote;
use App\Service\Cruise\Check\CruiseCheckCompanyService;
use App\Service\Cruise\Check\CruiseCheckSpecialService;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class H5Guard implements Guard
{
    protected $provider;
    protected $request;
    protected $token;
    protected $user;

    public function __construct(UserProvider $provider, Request $request)
    {
        $this->provider = $provider;
        $this->request  = $request;
        $this->token    = $this->request->header('authorization', '');
    }

    /**
     * 检查
     * @return bool|array
     */
    public function check()
    {
        if (!isset($this->decodeJwt()['user']) || !isset($this->decodeJwt()['user']['id'])) {
            return [
                'msg' => '获取用户信息失败'
            ];
        }

        if (!isset($this->decodeJwt()['user']['status']) || $this->decodeJwt()['user']['status'] == 1) {
            return [
                'msg' => '该用户已被禁用'
            ];
        }

        if (!isset($this->decodeJwt()['payload']['exp']) || $this->decodeJwt()['payload']['exp'] < time()) {
            return [
                'msg' => '登录状态已过期'
            ];
        }

        // 判断该用户下是否存在正常的供应商
        $normalFsCompanyIds = CruiseCheckSpecialService::getNormalFsCompanyIds($this->decodeJwt()['user']['id']);

        if (!count($normalFsCompanyIds)) {
            return [
                'msg' => '所在供应商没有权限，请联系管理员'
            ];
        }

        return true;
    }

    public function guest(): bool
    {
        if (!$this->token) {
            return true;
        }
        return false;
    }

    public function user()
    {
        $userInfo = array_merge([
            'permissions' => [],
        ], $this->decodeJwt()['user']);

        return (object)$userInfo;
    }

    public function id()
    {
        return $this->decodeJwt()['user']['id'];
    }

    public function validate(array $credentials = [])
    {
        // 验证用户凭证
    }

    public function setUser(Authenticatable $user)
    {
        // 设置当前登录的用户
        $this->user = $user;

        return $this;
    }

    public function decodeJwt()
    {
        $supplierAuthorizeKey = 'supplier_authorize_login:' . md5($this->token);

        return Cache::remember($supplierAuthorizeKey, 5 * 60, function () {
            return RmsUserRemote::decodeJwt();
        });
    }
}
